package org.example.l2;

import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;

import java.util.stream.IntStream;

public class graph2 {

    @Test
    void aa2() {
        //        char[][] from = CharHelper.from("[[\"1\",\"1\",\"1\",\"1\",\"0\"],[\"1\",\"1\",\"0\",\"1\",\"0\"],[\"1\",\"1\",\"0\",\"0\",\"0\"]]\n");
        char[][] from = CharHelper.from("[[\"1\",\"1\",\"0\",\"0\",\"0\"],[\"1\",\"1\",\"0\",\"0\",\"0\"],[\"0\",\"0\",\"1\",\"0\",\"0\"],[\"0\",\"0\",\"0\",\"1\",\"1\"]]");
        int i = numIslands(from);
        System.out.println(i);
    }

    private int numIslands(char[][] grid) {
        this.grid = grid;
        this.rows = grid.length;
        this.cols = grid[0].length;

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                char at = at(i, j);
                if (at == '1') {
                    dfs(i, j, new boolean[rows][cols]);
                    res++;
                }
            }
        }

        return res;
    }

    char[][] grid;
    int rows, cols, res;
    int[][] coordinate = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};


    void dfs(int row,
             int col,
             boolean[][] visited) {
        char at = at(row, col);
        if (at == '0') {
            return;
        }

        grid[row][col] = '*';
        visited[row][col] = true;

        for (int[] ints : coordinate) {
            int row2 = row + ints[0], col2 = col + ints[1];
            char b = at(row2, col2);
            if (b != '1') {
                continue;
            }

            if (visited[row2][col2]) {
                continue;
            }

            dfs(row2, col2, visited);
        }

        visited[row][col] = false;
    }

    char at(int row,
            int col) {
        if (row >= rows || row < 0) {
            return '*';
        }

        if (col >= cols || col < 0) {
            return '*';
        }

        return grid[row][col];
    }
}
